package com.example.licencecreate.controller;

import com.example.licencecreate.common.ResultMessage;
import com.example.licencecreate.utils.KeyTools;
import com.example.licencecreate.utils.SignTools;
import com.example.tass.licence.LicenceContent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ObjectOutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

@RestController
public class SignController {
    
    private LicenceContent licenceContent;
    private KeyTools keyTools;
    // 从配置文件读取用户信息
    
    public SignController(LicenceContent licenceContent, KeyTools keyTools) {
        this.licenceContent = licenceContent;
        this.keyTools = keyTools;
    }

    // 对用户信息进行签名并生成和用户(使用者)绑定的licence文件
    @GetMapping(value = "/generateLicence")
    public ResultMessage generateLicence() throws Exception {
        StringBuilder sb = new StringBuilder();
        sb.append(licenceContent.getVendor())
                .append(licenceContent.getUser())
                .append(licenceContent.getOrganization())
                .append(licenceContent.getIssuedTime())
                .append(licenceContent.getNotBeforeTime())
                .append(licenceContent.getNotAfterTime())
                .append(licenceContent.getAllowIp());
        // 使用私钥对信息licence信息进行签名 (被签名的信息示例：DingLiansunhongguangR&DThu Mar 30 19:00:00 GMT+08:00 2023Thu Mar 30 11:59:59 GMT+08:00 2023Fri Mar 31 11:59:59 GMT+08:00 2023192.168.20.154)
        byte[] sign = SignTools.sign(sb.toString().getBytes(StandardCharsets.UTF_8), keyTools.getPrivateKey());
        licenceContent.setSign(new String(sign));
        //ObjectOutputStream cos = new ObjectOutputStream(Files.newOutputStream(Paths.get("/opt/myLicence/licence.ser")));
        //ObjectOutputStream cos = new ObjectOutputStream(Files.newOutputStream(Paths.get("D:\\a_myFile\\workspace\\personal\\Java\\tass\\src\\main\\resources\\licence.ser")));
        ObjectOutputStream cos = new ObjectOutputStream(Files.newOutputStream(Paths.get(System.getProperty("user.home")+"\\licence.lic")));
        cos.writeObject(licenceContent);
        cos.close();
        return ResultMessage.newSuccessResult("生成licence成功,存放位置在用户主目录下,文件名为licence.lic");
    }
}
